package org.mklink.util;

import org.mklink.domain.ControlWrapper;
import javafx.application.Platform;
import javafx.scene.control.Control;
import javafx.scene.control.Labeled;
import javafx.scene.control.ListView;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: wyx
 * @Date: 2023/8/24 9:31
 */
public class UI {
    
    // 注册的Label控件集合
    private static final  ConcurrentHashMap<String, Control> registeredControls =  new ConcurrentHashMap<>();
    
    //label--------------------------------------------------------------
    public static void updateLabelText(String name, String text) {
        if (registeredControls.containsKey(name)) {
            Platform.runLater(() -> {
                ((Labeled)registeredControls.get(name)).setText(text);
            });
        }
    }
    
    //disable-------------------------------------------------------------
    
    /**
     * 设置控件是否禁用
     * @param disable
     * @param name
     */
    public static void setDisable(Boolean disable, String name){
        if(Objects.isNull(name) || name.isEmpty()){
            Platform.runLater(() -> {
                registeredControls.forEach((cname, control) -> control.setDisable(disable));
            });
        }
       else if (registeredControls.containsKey(name)) {
            Platform.runLater(() -> {
                registeredControls.get(name).setDisable(disable);
            });
        }
    }
    
    public static void setDisable(Boolean disable){
        setDisable(disable,"");
    }
    
    public static void setDisable(Boolean disable, List<String> filterNames){
        Platform.runLater(() -> {
           registeredControls.forEach((name, control) -> {
               if(filterNames == null || !filterNames.contains(name)){
                   control.setDisable(disable);
               }
           });
        });
    }
    
    public static <T extends Control> void registeredControls(ControlWrapper<T> ...control) {
        for (ControlWrapper<T> labelControlWrapper : control) {
            registeredControls.put(labelControlWrapper.getName(), labelControlWrapper.getControl());
        }
    }
    
    public static void addListViewItem(String name,String item){
        if(registeredControls.containsKey(name)){
            Platform.runLater(() -> {
                ListView<String> listView = (ListView<String>)registeredControls.get(name);
                listView.getItems().add(0,item);
            });
        }
    }
    
    //清空列表项
    public static void clearListViewItem(){
        registeredControls.forEach((name, control) -> {
            if(control instanceof ListView){
                Platform.runLater(() -> {
                    ((ListView)control).getItems().clear();
                });
            }
        });
    }
}
